import Taro, {Component, Config} from '@tarojs/taro';
import {View} from '@tarojs/components';
import './index.scss';
import {HxPost} from '../../service/http';
import shareImg from '../../assets/img/share.png';
import {
    AtButton, AtInputNumber
} from 'taro-ui';
import HxPage from '../../components/hxPage/hxPage';
import {timeWeekPipe} from "../../utils/utils";

export default class OrderFoodDetail extends Component<any, any> {
    config: Config = {
        // navigationBarTitleText: '缴费列表'
        navigationBarTitleText: ''
    };
    private canClick = true;

    constructor() {
        super();
        this.state = {
            cardId: '',
            menuDate: '',
            mealTimeId: '',
            mealTimeName: '',
            storeList: [],
            storeId: '',
            orderList: [],
            orderIndex: -1,
            foodList: [],
            selectFoodNum: -1,
            quantity: 1,
            maxQuantity: 1,
        };
    }

    // noinspection JSUnusedGlobalSymbols
    onShareAppMessage() {
        return {
            title: '广州二中一卡通充值缴费',
            path: '/pages/personCenter/index',
            imageUrl: shareImg
        };
    }

    componentDidMount() {
        const params = this.$router.params;
        const param = JSON.parse(params.param);
        this.setState({
            cardId: params.cardId,
            menuDate: params.date,
            mealTimeId: param.mealTimeId,
            mealTimeName: param.mealTimeName,
            orderIndex: Number(params.index),
            orderList: param.orderList,
        });
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                return HxPost('orderFoodRoom', {
                    menuDate: this.state['menuDate'],
                    mealTimeId: this.state['mealTimeId'],
                    cardId: '',
                });
            })
            .then((res: any) => {
                this.setState({
                    storeList: res['storeList'],
                });
                if (res['storeList'].length > 0) {
                    this.changeCanteen(this.state['orderIndex'] > -1 ? this.state['orderList'][this.state['orderIndex']].storeId : res['storeList'][0].storeId, true)
                } else {
                    return Promise.reject({retMsg: '可订餐食堂为空'})
                }
            })
            .catch((err) => {
                Taro.hideLoading();
                Taro.showModal({content: err.retMsg || '未知错误', showCancel: false}).catch();
            });
    }

    changeCanteen(storeId, isFirst) {
        this.setState({
            foodList: [],
            selectFoodNum: -1,
            quantity: 1,
        });
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                this.setState({
                    storeId
                })
                return HxPost('orderFoodMealMenu', {
                    menuDate: this.state['menuDate'],
                    storeId,
                    mealTimeId: this.state['mealTimeId'],
                });
            })
            .then((res: any) => {
                this.setState({
                    foodList: res['packageList'],
                });
                if (isFirst && this.state['orderIndex'] > -1) {
                    setTimeout(() => {
                        const selectFood = this.state['orderList'][this.state['orderIndex']]
                        this.selectFood(res['packageList'].findIndex(item => {
                            return item.packageId === selectFood.packageId
                        }))
                    })
                }
                Taro.hideLoading();
            })
            .catch((err) => {
                Taro.hideLoading();
                Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 3 * 1000}).catch();
            });
    }

    selectFood(index) {
        if (index > -1) {
            const selectFood = this.state['foodList'][index]
            const orderIndex = this.state['orderList'].findIndex(item => item.packageId === selectFood.packageId)
            const historyData = this.state['orderList'][orderIndex]
            this.setState({
                selectFoodNum: index,
                quantity: historyData ? historyData.quantity : 1,
                maxQuantity: Number(selectFood.tatolQuantity) - Number(selectFood.amountQuantity),
                orderIndex
            });
        }
    }

    orderFood(action, quantity) {
        const item = this.state['orderList'][this.state['orderIndex']]
        let msg = '确定预订餐吗？';
        if (action === 'M') {
            msg = '确定修改订餐吗？';
        }
        if (action === 'D') {
            msg = '确定退订该笔订餐吗？';
        }
        return Taro.showModal({
            title: '',
            content: msg,
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定'
        })
            .then((res) => {
                if (res.confirm) {
                    return Taro.showLoading({title: '加载中...', mask: true});
                } else {
                    return Promise.reject('cancel');
                }
            })
            .then(() => {
                const param = {
                    menuDate: this.state['menuDate'],
                    cardId: this.state['cardId'],
                    storeId: this.state['storeId'],
                    mealTimeId: this.state['mealTimeId'],
                    packageId: this.state['foodList'][this.state['selectFoodNum']].packageId,
                    quantity: quantity,
                    mealOrderId: action === 'A' ? '' : item['mealOrderId'],
                    opFlag: action
                }
                return HxPost('orderFood', param);
            })
            .then((res: any) => {
                Taro.hideLoading();
                const newFoodList = this.state['foodList'];
                const selectNum = this.state['selectFoodNum'];
                const orderList = this.state['orderList'];
                if (action === 'M') {
                    newFoodList[selectNum].amountQuantity += (quantity - item.quantity);
                    orderList[this.state['orderIndex']].quantity = quantity;
                }
                if (action === 'A') {
                    newFoodList[selectNum].amountQuantity += Number(quantity);
                    setTimeout(() => {
                        Taro.navigateBack();
                    }, 2000)
                }
                if (action === 'D') {
                    newFoodList[selectNum].amountQuantity -= Number(quantity);
                    orderList.splice(this.state['orderIndex'], 1);
                }
                this.setState({
                    foodList: newFoodList,
                    selectFoodNum: -1,
                    maxQuantity: Number(newFoodList[selectNum].tatolQuantity) - Number(newFoodList[selectNum].amountQuantity),
                    orderList,
                });
                Taro.showToast({title: res.retMsg, icon: 'none', duration: 3 * 1000}).catch();
                return Promise.resolve();
            })
            .catch((err) => {
                console.log(err)
                if (err !== 'cancel') {
                    Taro.hideLoading();
                    Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 3 * 1000}).catch();
                }
                return Promise.reject()
            });
    }

    changeQuantity(e) {
        if (this.state['orderIndex'] > -1) {
            if (this.canClick) {
                this.canClick = false;
                this.orderFood('M', e)
                    .then(() => {
                        this.canClick = true;
                    })
                    .catch(() => {
                        this.canClick = true;
                    });
            }
        } else {
            this.setState({
                quantity: e
            })
        }
    }

    render() {
        const {
            menuDate,
            mealTimeName,
            storeId,
            storeList,
            foodList,
            selectFoodNum,
            quantity,
            maxQuantity,
            orderIndex,
        } = this.state;
        return (
            <HxPage>
                <View className="orderFoodDetail">
                    <View className="orderFoodDetail_header">
                        {timeWeekPipe(menuDate)}<View>{mealTimeName}</View>
                    </View>
                    <View className="orderFoodDetail_store">
                        {
                            storeList.map(item =>
                                <View onClick={this.changeCanteen.bind(this, item.storeId)}
                                      className={item.storeId === storeId ? ' orderFoodDetail_store_active' : ''}
                                      key={item.storeId}>{item.storeName}</View>
                            )
                        }
                    </View>
                    <View className="orderFoodDetail_title">请选择套餐</View>
                    <View className="orderFoodDetail_list_wrap">
                        <View className="orderFoodDetail_list">
                            {
                                foodList.length === 0 ?
                                    <View className="orderFoodDetail_list_tips">该餐次未开放菜单</View>
                                    :
                                    foodList.map((item, index) => (
                                        item.amountQuantity === item.tatolQuantity ?
                                            <View key={index}
                                                  className="orderFoodDetail_list_item orderFoodDetail_list_item_disable"
                                            >
                                                <View
                                                    className="orderFoodDetail_list_item_header"
                                                >
                                                    <View>{item.packageName}</View>
                                                    <View>({item.amountQuantity}/{item.tatolQuantity})</View>
                                                </View>
                                                <View className="orderFoodDetail_list_item_con">
                                                    {item.dishDetail}
                                                </View>
                                            </View>
                                            :
                                            <View key={index}
                                                  className={index === selectFoodNum ? 'orderFoodDetail_list_item orderFoodDetail_list_item_active' : 'orderFoodDetail_list_item'}
                                                  onClick={this.selectFood.bind(this, index)}
                                            >
                                                <View
                                                    className="orderFoodDetail_list_item_header"
                                                >
                                                    <View>{item.packageName}</View>
                                                    <View>({item.amountQuantity}/{item.tatolQuantity})</View>
                                                </View>
                                                <View className="orderFoodDetail_list_item_con">
                                                    {item.dishDetail}
                                                </View>
                                            </View>
                                    ))
                            }
                        </View>
                    </View>

                    <View className="orderFoodDetail_footer">
                        <View className="orderFoodDetail_footer_left">
                            {
                                selectFoodNum < 0 ? '' :
                                    <View>
                                        ¥{foodList[selectFoodNum].price} x
                                        <AtInputNumber
                                            type="digit"
                                            min={1}
                                            max={maxQuantity}
                                            step={1}
                                            value={quantity}
                                            disabled={!this.canClick}
                                            onChange={this.changeQuantity.bind(this)}
                                        />
                                    </View>
                            }

                        </View>
                        <AtButton
                            className="orderFoodDetail_footer_button"
                            disabled={selectFoodNum < 0}
                            onClick={this.orderFood.bind(this, orderIndex > -1 ? 'D' : 'A', quantity)}
                        >{orderIndex > -1 ? '退订' : '预订'}</AtButton>
                    </View>
                </View>
            </HxPage>
        );
    }
}
